package com.meiyuetao.myt.md.service;

import java.util.Arrays;
import java.util.Date;
import java.util.List;

import lab.s2jh.auth.dao.UserDao;
import lab.s2jh.auth.entity.User;
import lab.s2jh.core.dao.BaseDao;
import lab.s2jh.core.service.BaseService;
import lab.s2jh.core.service.Validation;

import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.google.common.collect.Lists;
import com.meiyuetao.myt.md.dao.PersonalMessageDao;
import com.meiyuetao.myt.md.dao.PersonalMessageItemDao;
import com.meiyuetao.myt.md.entity.PersonalMessage;
import com.meiyuetao.myt.md.entity.PersonalMessageItem;

@Service
@Transactional
public class PersonalMessageService extends BaseService<PersonalMessage, Long> {

    @Autowired
    private PersonalMessageDao personalMessageDao;

    @Autowired
    private PersonalMessageItemDao personalMessageItemDao;

    @Autowired
    private UserDao userDao;

    @Override
    protected BaseDao<PersonalMessage, Long> getEntityDao() {
        return personalMessageDao;
    }

    /**
     * 发布消息
     * 
     * @param entity
     * @return 发布成功返回NULL, 失败返回对应错误信息（String）
     */
    public void publish(PersonalMessage entity) {
        entity.setPublishTime(new Date());
        save(entity);// 先保存主对象

        List<String> notExistUsers = Lists.newArrayList();
        String targetUsers = entity.getTargetUsers();
        if (StringUtils.isNotBlank(targetUsers)) {// 目标用户 不为空
            String[] targetUsersArr = targetUsers.split(" ");
            if (ArrayUtils.isNotEmpty(targetUsersArr)) {// 目标用户根据空格分割后 不为空
                for (String targetUser : targetUsersArr) {
                    List<User> users = userDao.findBySigninid(targetUser);
                    if (!users.isEmpty() && users.size() <= 1) {// 目标用户存在 并 只有一个
                        PersonalMessageItem item = new PersonalMessageItem();
                        item.setTargetUser(users.get(0));
                        item.setPersonalMessage(entity);
                        personalMessageItemDao.save(item); // 保存条目
                    } else {
                        notExistUsers.add(targetUser);
                    }
                }
            }
        }
        Validation.isTrue(notExistUsers.isEmpty(), "目标用户" + Arrays.toString(notExistUsers.toArray()) + "不存在");
    }
}
